<!-- 区域架构图 -->
<template>
  <!-- class="graph-box" -->
  <div :style="chartStyle">
    <div id="graphContent"></div>
  </div>
</template>

<script>
import { Graph, Path } from '@antv/x6'
import Hierarchy from '@antv/hierarchy'
// import insertCss from 'insert-css'

const THEME_COLOR = '#006db8';
const SECOND_AREA_BG = '#cce2f1'
export default {
  props: {
    chartStyle: {
      type: Object,
    },
    graphData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      graph: null,
      graphStyle: {
        width: this.chartStyle.width,
        height: this.chartStyle.height
      },
    }
  },

  watch: {
    graphData() {
      const timer = setTimeout(() => {
        this.render();
        clearTimeout(timer);
      },400)
    },
  },

  mounted() {
    this.graphInit();
    this.initSize();
    const timer = setTimeout(() => {
      this.render();
      clearTimeout(timer);
    },400)
  },

  methods: {
    // 注册中心区域
    registerArea() {
      Graph.registerNode(
        'center-area', //名字
        {
          inherit: 'circle',
          markup: [
            {
              tagName: 'circle',
              selector: 'body', //选择器
            },
            {
              tagName: 'text',
              selector: 'label',
            },
          ],
          attrs: {
            body: {
              // rx: 6,
              // ry: 6,
              stroke: '#fff',
              // fill: THEME_COLOR,
              fill: {
                type: 'linearGradient',
                stops: [
                  { offset: '0%',  color: '#2cabe6' },
                  { offset: '100%', color: THEME_COLOR },
                ],
              },
              strokeWidth: 2,
            },
            label: {
              fontSize: 14,
              fill: '#fff',
              fontWeight: 700
            },
          },
        },
        true,
      )
    },
    
    //注册二级区域
    registerSecondArea() {
      Graph.registerNode(
        'second-area',
        {
          inherit: 'rect',
          markup: [
            {
              tagName: 'rect',
              selector: 'body',
            },
            {
              tagName: 'text',
              selector: 'label',
            },
          ],
          attrs: {
            body: {
              rx: 6,
              ry: 6,
              stroke: '#5F95FF',
              fill: SECOND_AREA_BG,
              strokeWidth: 0,
            },
            label: {
              fontSize: 14,
              fill: THEME_COLOR,
              fontWeight: 700
            },
          },
        },
        true,
      )
    },

    //注册子区域
    registerChildArea() {
      Graph.registerNode(
        'area-child',
        {
          inherit: 'rect',
          markup: [
            {
              tagName: 'rect',
              selector: 'body',
            },
            {
              tagName: 'text',
              selector: 'label',
            },
          ],
          attrs: {
            body: {
              rx: 6,
              ry: 6,
              stroke: THEME_COLOR,
              fill: '#fff',
              strokeWidth: 1,
            },
            label: {
              fontSize: 14,
              fill: THEME_COLOR,
              fontWeight: 700
            },
          },
        },
        true,
      )
    },

    //注册连接器
    registerConnector() {
      // 连接器
      Graph.registerConnector(
        'mindmap',
        (sourcePoint, targetPoint, routerPoints, options) => {
          const midX = sourcePoint.x + 10
          const midY = sourcePoint.y
          const ctrX = (targetPoint.x - midX) / 5 + midX
          const ctrY = targetPoint.y
          const pathData = `
          M ${sourcePoint.x} ${sourcePoint.y}
          L ${midX} ${midY}
          Q ${ctrX} ${ctrY} ${targetPoint.x} ${targetPoint.y}
          `
          return options.raw ? Path.parse(pathData) : pathData
        },
        true,
      )
    },
    
    //注册边
    registerEdge() {
      // 边
      Graph.registerEdge(
        'mindmap-edge',
        {
          inherit: 'edge',
          connector: {
            name: 'mindmap',
          },
          attrs: {
            line: {
              targetMarker: '',
              stroke: THEME_COLOR,
              strokeWidth: 2,
            },
          },
          zIndex: 0,
        },
        true,
      )
    },
    graphInit() {
      this.registerArea();
      this.registerSecondArea();
      this.registerChildArea();
      this.registerConnector();
      this.registerEdge();

      this.graph = new Graph({
        container: document.getElementById('graphContent'),
        connecting: {
          connectionPoint: 'anchor',
        },
        selecting: {
          enabled: false,
        },
        keyboard: {
          enabled: false,
        },
        autoResize: true,
        panning: true,
        interacting: function(cellView) {
          return {
            nodeMovable: false, // 节点是否可以被移动。
          }
        }
      });
    },

    render() {
      const result = Hierarchy.mindmap(this.graphData, {
        direction: 'H',
        getHeight(d) {
          return d.height
        },
        getWidth(d) {
          return d.width
        },
        getHGap() {
          return 40
        },
        getVGap() {
          return 20
        },
        getSide: () => {
          return 'right'
        },
      })
      const cells = []
      const traverse = (hierarchyItem) => {
        if (hierarchyItem) {
          const { data, children } = hierarchyItem
          cells.push(
            this.graph.createNode({
              id: data.id,
              x: hierarchyItem.x,
              y: hierarchyItem.y,
              width: data.width,
              height: data.height,
              label: data.label,
              type: data.type,
              shape: data.type,
            }),
          )
          if (children) {
            children.forEach((item) => {
              const { id, data } = item
              cells.push(
                this.graph.createEdge({
                  shape: 'mindmap-edge',
                  source: {
                    cell: hierarchyItem.id,
                    anchor:
                      data.type === 'area-child'
                        ? {
                            name: 'right',
                            args: {
                              dx: -16,
                            },
                          }
                        : {
                            name: 'center',
                            args: {
                              dx: '25%',
                            },
                          },
                  },
                  target: {
                    cell: id,
                    anchor: {
                      name: 'left',
                    },
                  },
                }),
              )
              traverse(item)
            })
          }
        }
      }
      traverse(result)
      this.graph.resetCells(cells)
      this.graph.centerContent();
    },

    //监听窗口大小变化
    initSize() {
      window.onresize = () => {
        this.throttle(this.graph.centerContent(), 200);
      }
    },
    //节流
    throttle(fn, delay) {
      let flag = true;
      return function (e) {
        if(flag) {
          setTimeout(() => {
            //到规定时间后执行函数，同时flag = true
            fn.call(this, arguments);
          }, delay);
        }
        //防止一直执行
        flag = false;
      }
    },
  },
}
</script>
<style scoped>
  .graph-box {
    /* width: 100%;
    height: calc(395px - 40px - 44px); */
  }
</style>